//! 中国本土化数据生成测试
//! 
//! 测试中文姓名、地址、身份证号等中国特色数据的生成

use dataforge::generators::name;
use dataforge::generators::address;
use dataforge::generators::number;
use dataforge::generators::internet;
use dataforge::generators::datetime;
use chrono::Datelike;
use rand::Rng;

#[test]
fn test_chinese_names_basic() {
    for _ in 0..10 {
        let name = name::zh_cn_fullname();
        assert!(!name.is_empty());
        assert!(name.chars().count() >= 2);
        assert!(name.chars().count() <= 4);
        println!("中文姓名: {}", name);
    }
}

#[test]
fn test_chinese_names_gender() {
    // 测试男性姓名
    for _ in 0..5 {
        let name = name::zh_cn_male_fullname();
        assert!(!name.is_empty());
        println!("男性姓名: {}", name);
    }
    
    // 测试女性姓名
    for _ in 0..5 {
        let name = name::zh_cn_female_fullname();
        assert!(!name.is_empty());
        println!("女性姓名: {}", name);
    }
}

#[test]
fn test_chinese_names_components() {
    // 测试姓氏
    for _ in 0..10 {
        let lastname = name::zh_cn_lastname();
        assert!(!lastname.is_empty());
        // 大部分中文姓氏是单字， 有复姓的场景
        assert!(lastname.chars().count() >= 1);
        assert!(lastname.chars().count() <= 2);
        println!("中文姓氏: {}", lastname);
    }
    
    // 测试名字
    for _ in 0..10 {
        let firstname = name::zh_cn_firstname();
        assert!(!firstname.is_empty());
        assert!(firstname.chars().count() >= 1);
        assert!(firstname.chars().count() <= 2);
        println!("中文名字: {}", firstname);
    }
}

#[test]
fn test_chinese_addresses_province() {
    for _ in 0..10 {
        let province = address::zh_province();
        assert!(!province.is_empty());
        assert!(province.ends_with("省") || province.ends_with("市") || 
                province.ends_with("区") || province.contains("自治区"));
        println!("省份: {}", province);
    }
}

#[test]
fn test_chinese_addresses_city() {
    for _ in 0..10 {
        let city = address::zh_city();
        assert!(!city.is_empty());
        println!("城市: {}", city);
    }
}

#[test]
fn test_chinese_addresses_complete() {
    for _ in 0..5 {
        let addr = address::zh_address();
        assert!(!addr.is_empty());
        assert!(addr.len() > 10); // 中文地址通常比较长
        println!("完整地址: {}", addr);
    }
}

#[test]
fn test_chinese_phone_numbers() {
    for _ in 0..10 {
        let phone = number::phone_number_cn();
        assert!(!phone.is_empty());
        assert!(phone.starts_with("1")); // 中国手机号以1开头
        assert_eq!(phone.len(), 11); // 中国手机号11位
        
        // 验证第二位数字（3-9）
        let second_digit = phone.chars().nth(1).unwrap();
        assert!(second_digit >= '3' && second_digit <= '9');
        
        println!("中国手机号: {}", phone);
    }
}

#[test]
fn test_chinese_id_cards() {
    for _ in 0..10 {
        let id_card = number::id_card_cn();
        assert!(!id_card.is_empty());
        assert_eq!(id_card.len(), 18); // 中国身份证号18位
        
        // 前17位应该是数字
        let first_17: String = id_card.chars().take(17).collect();
        assert!(first_17.chars().all(|c| c.is_ascii_digit()));
        
        // 最后一位是数字或X
        let last_char = id_card.chars().last().unwrap();
        assert!(last_char.is_ascii_digit() || last_char == 'X');
        
        println!("身份证号: {}", id_card);
    }
}

#[test]
fn test_chinese_postal_codes() {
    for _ in 0..10 {
        let postal = address::zh_postal_code();
        assert!(!postal.is_empty());
        assert_eq!(postal.len(), 6); // 中国邮编6位
        assert!(postal.chars().all(|c| c.is_ascii_digit()));
        
        println!("邮政编码: {}", postal);
    }
}

#[test]
fn test_chinese_company_names() {
    for _ in 0..5 {
        let company = name::zh_cn_company();
        assert!(!company.is_empty());
        assert!(company.contains("有限公司") || company.contains("股份有限公司") || 
                company.contains("科技") || company.contains("集团"));
        println!("公司名称: {}", company);
    }
}

#[test]
fn test_chinese_bank_cards() {
    for _ in 0..5 {
        let card = number::bank_card_cn();
        assert!(!card.is_empty());
        assert!(card.len() >= 16); // 银行卡号至少16位
        assert!(card.len() <= 19); // 银行卡号最多19位
        assert!(card.chars().all(|c| c.is_ascii_digit()));
        println!("银行卡号: {}", card);
    }
}

#[test]
fn test_chinese_coordinates() {
    for _ in 0..5 {
        let (lat, lng) = address::china_coordinate();
        
        // 中国大陆的大致坐标范围
        assert!(lat >= 18.0 && lat <= 54.0); // 纬度
        assert!(lng >= 73.0 && lng <= 135.0); // 经度
        
        println!("中国坐标: ({:.6}, {:.6})", lat, lng);
    }
}

#[test]
fn test_chinese_datetime_formats() {
    // 测试生日（年龄合理范围）
    for _ in 0..10 {
        let birthday = datetime::birthday();
        assert!(!birthday.is_empty());
        
        // 解析生日并验证年龄合理性
        if let Ok(date) = chrono::NaiveDate::parse_from_str(&birthday, "%Y-%m-%d") {
            let today = chrono::Utc::now().date_naive();
            let age_days = today.signed_duration_since(date).num_days();
            let age_years = age_days / 365;
            
            assert!(age_years >= 0 && age_years <= 120);
            println!("生日: {} (年龄约: {}岁)", birthday, age_years);
        }
    }
}

#[test]
fn test_chinese_data_integration() {
    // 生成一个完整的中国用户档案
    for i in 0..3 {
        let profile = serde_json::json!({
            "id": i + 1,
            "name": name::zh_cn_fullname(),
            "gender": if i % 2 == 0 { "男" } else { "女" },
            "id_card": number::id_card_cn(),
            "phone": number::phone_number_cn(),
            "email": internet::email(),
            "address": {
                "province": address::zh_province(),
                "city": address::zh_city(),
                "detail": address::zh_address(),
                "postal_code": address::zh_postal_code()
            },
            "work": {
                "company": name::zh_cn_company(),
                "salary": number::salary(),
                "position": "软件工程师"
            },
            "finance": {
                "bank_card": number::bank_card_cn(),
                "balance": number::price()
            },
            "timestamps": {
                "birthday": datetime::birthday(),
                "created_at": datetime::iso8601()
            }
        });
        
        // 验证数据完整性
        assert!(profile["name"].is_string());
        assert!(profile["id_card"].is_string());
        assert!(profile["phone"].is_string());
        assert!(profile["address"]["province"].is_string());
        assert!(profile["work"]["company"].is_string());
        assert!(profile["finance"]["bank_card"].is_string());
        
        println!("中国用户档案 {}: {}", i + 1, serde_json::to_string_pretty(&profile).unwrap());
    }
}

#[test]
fn test_chinese_business_data() {
    // 生成企业信息
    for i in 0..3 {
        let mut rng = rand::thread_rng();
        let registration_code: u64 = rng.gen_range(100000000000000000..=999999999999999999);
        
        let business = serde_json::json!({
            "company_id": i + 1,
            "name": name::zh_cn_company(),
            "legal_person": name::zh_cn_fullname(),
            "registration_code": format!("{:018}", registration_code),
            "address": address::zh_address(),
            "contact": {
                "phone": number::phone_number_cn(),
                "email": internet::email()
            },
            "business_scope": "软件开发、技术咨询、系统集成",
            "registered_capital": number::random_int(100, 10000),
            "established_date": datetime::date_between("2010-01-01", "2023-12-31")
        });
        
        assert!(business["name"].is_string());
        assert!(business["legal_person"].is_string());
        assert!(business["registration_code"].is_string());
        assert!(business["address"].is_string());
        
        println!("企业信息 {}: {}", i + 1, serde_json::to_string_pretty(&business).unwrap());
    }
}

#[test]
fn test_chinese_education_data() {
    // 生成教育相关数据
    let schools = ["清华大学", "北京大学", "复旦大学", "上海交通大学", "浙江大学"];
    let majors = ["计算机科学与技术", "软件工程", "信息安全", "人工智能", "数据科学"];
    
    for i in 0..3 {
        let education = serde_json::json!({
            "student_id": format!("2020{:06}", i + 1),
            "name": name::zh_cn_fullname(),
            "school": schools[i % schools.len()],
            "major": majors[i % majors.len()],
            "grade": 2020 + (i % 4),
            "gpa": format!("{:.2}", number::random_float(2.0, 4.0)),
            "phone": number::phone_number_cn(),
            "hometown": address::zh_province()
        });
        
        assert!(education["name"].is_string());
        assert!(education["school"].is_string());
        assert!(education["major"].is_string());
        assert!(education["phone"].is_string());
        
        println!("学生信息 {}: {}", i + 1, serde_json::to_string_pretty(&education).unwrap());
    }
}

#[test]
fn test_chinese_data_uniqueness() {
    let mut names = std::collections::HashSet::new();
    let mut phones = std::collections::HashSet::new();
    let mut id_cards = std::collections::HashSet::new();
    
    for _ in 0..100 {
        names.insert(name::zh_cn_fullname());
        phones.insert(number::phone_number_cn());
        id_cards.insert(number::id_card_cn());
    }
    
    // 验证数据的唯一性
    assert!(names.len() >= 90); // 姓名重复率应该很低
    assert!(phones.len() >= 95); // 手机号重复率应该极低
    assert!(id_cards.len() >= 95); // 身份证号重复率应该极低
    
    println!("生成了 {} 个不同的姓名", names.len());
    println!("生成了 {} 个不同的手机号", phones.len());
    println!("生成了 {} 个不同的身份证号", id_cards.len());
}

#[test]
fn test_chinese_regional_distribution() {
    let mut provinces = std::collections::HashMap::new();
    
    for _ in 0..100 {
        let province = address::zh_province();
        *provinces.entry(province).or_insert(0) += 1;
    }
    
    // 应该有多个不同的省份
    assert!(provinces.len() >= 10);
    
    println!("省份分布:");
    for (province, count) in provinces.iter().take(10) {
        println!("  {}: {} 次", province, count);
    }
}